package com.nbpt.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.Nullable;
import android.util.Log;

public class AccountDBHelp extends SQLiteOpenHelper {

    private Context mContext;
    private final static String DB_NAME = "account.db";
    private final static String TABLE_NAME = "tb_users";
    public final static int VERSION_1 = 1;
    private final String sql_create_table ="create table tb_users\n" +
            "(\n" +
            "id integer primary key AUTOINCREMENT, \n" +
            "username varchar(25) unique, \n" +
            "password varchar(25),\n" +
            "phone varchar(11),\n" +
            "nc text,\n"+
            "xb text\n"+
            ");";

    public AccountDBHelp(Context mContext, int version) {
        super(mContext, DB_NAME, null, version);
        this.mContext = mContext;
    }

    private final String sql_insert_table ="INSERT INTO tb_users (id,username,password,phone,nc,xb)\n" +
            "VALUES ('1','admin','123','152512231','bztwc','1');";

    public String getUsername(Cursor cursor)
    {
        return cursor.getString(1);
    }

    public  String getPassword(Cursor cursor)
    {
        return cursor.getString(2);
    }

    public Cursor select(String where, String orderby) {
        StringBuilder stringBuilder = new StringBuilder(" SELECT * FROM " + TABLE_NAME);
        if (where != null) {
            stringBuilder.append(" WHERE ");
            stringBuilder.append(where);
        }
        if (orderby != null) {
            stringBuilder.append(" ORDER BY ");
            stringBuilder.append(orderby);
        }
        Log.d("DB",stringBuilder.toString());
        return  getWritableDatabase().rawQuery(stringBuilder.toString(),null);
    }

    public long insert(String name,String password,String phone,String nc,int xb)
    {
        ContentValues cv = new ContentValues();

        cv.put("username",name);
        cv.put("password",password);
        cv.put("phone",phone);
        cv.put("nc",nc);
        cv.put("xb",xb);

        return getWritableDatabase().insert("tb_users","",cv);
    }



    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(sql_create_table);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }

    public long update(String id,String nc) {
        ContentValues cv = new ContentValues();
        cv.put("nc",nc);
        String[] whereValue={id};
        return getWritableDatabase().update("tb_users",cv,"id=?",whereValue);
    }
}
